# coding=utf-8 ################################################################
import socket
import database
import random
import struct
import time
import exchange
import utils

def client():
    db = database.get()
    
    # Get peer
    db.execute("BEGIN IMMEDIATE")
    num_peers, = db.execute("SELECT COUNT(*) FROM peers").fetchone()
    if num_peers == 0:
        db.commit()
        return
    rand_peer = random.randint(0, num_peers-1)
    peerid, ip, port = db.execute("SELECT id, ip, port FROM peers "+
                              "ORDER BY id LIMIT 1 OFFSET ?",
                              (rand_peer,)).fetchone()
    db.commit()
    
    ip_str = ".".join(map(str, struct.unpack("BBBB", ip)))
    print("%s %d"%(ip_str, port))
    
    s = None
    try:
        s = socket.create_connection( (ip_str, port) )
        exchange.do_exchange_client(s, peerid)
        s.close()
        now = int(time.mktime(time.gmtime()))
        db.execute("UPDATE peers SET last_seen=? WHERE id=?", (now, peerid) )
    except socket.error as e:
        print("socket.error FAIL")
        if s: s.close()
        utils.delete_peer(db, peerid)
    except utils.ValidateDataError as e:
        print("RemoteDataError FAIL")
        utils.delete_peer(db, peerid)
    db.close()

def main():
    while True:
        client()
        for n in range(10):
            time.sleep(1)


if __name__ == '__main__':
    main()
